package controller;

import dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设定编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        //获取表单数据
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        System.out.println("account = " + account);
        System.out.println("password = " + password);
        //七天免密登录
        Cookie cookie = new Cookie("nameinfo", URLEncoder.encode(account + "-" + password, "utf-8"));
        //一天免登录，待验证remember
        cookie.setMaxAge(24 * 60 * 60);
        //增加Cookie到responce
        resp.addCookie(cookie);

        String error;
        //账号密码的非空校验   trim去空格
        if (account == null || account.trim().length() == 0 || password == null || password.trim().length() == 0) {
            //告知用户不能为空，同时用户依然停留在登录界面
            error = "用户名或密码不能为空！";
            //资源的跳转：  重定向  转发
            //重定向：根据当前的url进行资源的跳转  /表示是web容器的根路径   但是我们自己想在跳转url的同时携带信息
//            resp.sendRedirect(req.getContextPath() + "/html/*");
            //转发：根据url进行服务器内部资源的转发，此时可以共享信息（req，resp）
            req.setAttribute("error", error);
            //创建一个分发器，转发到登录页面资源
//            RequestDispatcher dispatcher = req.getRequestDispatcher("/loginPage");
//            dispatcher.forward(req,resp);
            req.getRequestDispatcher("/LoginPageServlet").forward(req, resp);

        } else {
            //校验账号密码是否正确
            StudentDao userDao = new StudentDao();
            boolean b = userDao.loginQuery(account, password);

            if (b) {
                //返回true表示登陆成功，跳转到首页
                req.setAttribute("name", account);
                //重定向
                req.getRequestDispatcher("home.jsp").forward(req, resp);
                System.out.println(account + "登陆成功！");
            } else {
                //返回false表示登陆失败，重新返回登录页面，并告知用户名密码错误
                error = "账号或密码错误！";
                req.setAttribute("error", error);
                //转发
                req.getRequestDispatcher("/LoginPageServlet").forward(req, resp);
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
